package cn.edu.cqvie.atc.hash;

import java.math.BigInteger;

/**
 * 文件描述
 *
 * @author Zheng Shaohong
 */
public class HashTable {

    private Info[] arr;

    public HashTable() {
        this.arr = new Info[100];
    }

    public HashTable(Info[] arr) {
        this.arr = arr;
    }


    public HashTable(int maxSize) {
        this.arr = new Info[maxSize];
    }

    /**
     * 插入数据
     * @param info
     */
    public void insert(Info info) {
        // 获得关键字
        String key = info.getKey();
        // 关键字锁自定的哈希数
        int hashVal = hashCode(key);
        // 如果这个索引已经被占用，而且里面是一个未被删除的的数据
        while (arr[hashVal] != null && arr[hashVal].getName() != null) {
            //递加
            ++ hashVal;
            //循环
            hashVal %= arr.length;
        }
        arr[hashVal] = info;

    }

    /**
     * 查找数据
     * @param key
     * @return
     */
    public Info find(String key) {
        int hashVal = hashCode(key);
        while (arr[hashVal] != null) {
            if (arr[hashVal].getKey().equals(key)) {
                return arr[hashVal];
            }
            ++ hashVal;
            hashVal %= arr.length;
        }
        return null;
    }

    /**
     * 删除数据
     * @param key
     * @return
     */
    public Info delete(String key) {
        int hashVal = hashCode(key);
        while (arr[hashVal] != null) {
            if (arr[hashVal].getKey().equals(key)) {
                Info tmp = arr[hashVal];
                tmp.setName(null);
                return tmp;
            }
            ++ hashVal;
            hashVal %= arr.length;
        }
        return null;
    }


    public int hashCode(String key) {
//        int hashVal = 0;
//        for (int i = key.length() - 1; i >= 0; i--) {
//            int letter = key.charAt(i) - 96;
//            hashVal += letter;
//        }
//        return hashVal;
        BigInteger hashVal = new BigInteger("0");
        BigInteger pow27 = new BigInteger("1");
        for  (int i=key.length() -1; i >= 0; i--) {
            BigInteger letter = new BigInteger(String.valueOf(key.charAt(i) - 96));
            hashVal = hashVal.add(letter.multiply(pow27));
            pow27 = pow27.multiply(new BigInteger(String.valueOf(27))) ;
        }
        return hashVal.mod(new BigInteger(String.valueOf(arr.length))).intValue();
    }

    public static void main(String[] args) {

        HashTable ht = new HashTable();
        ht.insert(new Info("a", "张三"));
        ht.insert(new Info("ct", "李四"));
        ht.insert(new Info("bbb", "王五"));

        System.out.println(ht.find("a").getName());

        ht.delete("bbb");
        System.out.println(ht.find("bbb").getName());

    }
}
